const TOOLBAR =[
	{content:"过滤条件", icon:"el-icon-search",type:""},
	{content:"添加", icon:"el-icon-document-add",type:"primary"},
	// {content:"删除", icon:"el-icon-delete",type:"danger"},
]
const COLUMNS = [
	{prop:"username", label:"姓名",width:"80"},
	{prop:"sex", label:"性别",width:"50"},
	{prop:"birthday", label:"生日",width:"100"},
	{prop:"phone", label:"手机号",width:"100"},
	{prop:"address", label:"地址",width:"250"},
	{prop:"dept", label:"部门",width:"80"},
	{prop:"position", label:"职位",width:"80"},	
	{prop:"ismanager", label:"部门经理",width:"80"},
	{prop:"isleader", label:"主管",width:"50"},
	{prop:"employdate", label:"入职日期",width:"100"},
	{prop:"leavedate", label:"离职日期",width:"100"},
	{prop:"status", label:"状态",width:"80"},
	{prop:"workstatus", label:"在职状态",width:"80"},
	{prop:"workplace", label:"工作地点",width:"80"},	
	{prop:"isactive", label:"激活",width:"50"},
	
]

let validate = {
    validatePass: (rule, value, callback) => {
        if (value !== app.userForm.password) {
            callback(new Error('两次输入密码不一致!'));
        } else if (value.length < 6) {
			callback(new Error('密码不能小于六位!'));
		} else {
            callback();
        }
    }
};
const rules = {
    deptname: [
        {required: true, message: '请输入正确的名称！', trigger: 'blur'}
    ],
	type: [
	    {required: true, message: '请选择类别！', trigger: 'blur'}
	]
   
};


const userRules = {
    username: [
        {required: true, message: '请输入姓名', trigger: 'blur'}
    ],
    birthday: [
        {required: true, message: '请输入生日', trigger: 'blur'}
    ],
    address: [
        {required: true, message: '请输入地址', trigger: 'blur'}
    ],
    sex: [
        {required: true, message: '请选择性别', trigger: 'change'}
    ],
    isactive: [
        {required: true, message: '请设定激活状态', trigger: 'change'}
    ],
    dept_id: [
        {required: true, message: '请设定部门', trigger: 'change'}
    ],
	positionid: [
	    {required: true, message: '请设定职位', trigger: 'change'}
	],
    employdate: [
        {required: true, message: '请设定入职日期', trigger: 'blur'}
    ],
	status: [
	    {required: true, message: '请设定状态', trigger: 'change'}
	],
	workstatus: [
	    {required: true, message: '请设定在职状态', trigger: 'change'}
	],
	workplace: [
	    {required: true, message: '请设定工作地点', trigger: 'change'}
	],
	ismanager: [
        {required: true, message: '请设定是否是部门经理', trigger: 'change'}
    ],
    isleader: [
        {required: true, message: '请设定是否是部门主管', trigger: 'change'}
    ],
    phone: [
        {required: true, message: '请输入手机号', trigger: 'blur'}
    ],
    password: [
        {required: true, message: '请输入密码', trigger: 'blur'}
    ],
    repassword: [
        {validator: validate.validatePass, trigger: 'blur'}
    ]
};
			
let app = new Vue({
    el: "#app",
    data() {
        return {
        	leftbar_show:true,
			uploadurl:axios.defaults.baseURL + "api/image/upload/idcard/",
			headers: {
				Token: localStorage.getItem('TOKEN'),
				UserID: localStorage.getItem('USERID')
			},
			// 添加、编辑标识
			action:"",
			tableHeight:window.innerHeight - 180,
			toolbar:TOOLBAR,
			tablecolums:COLUMNS,
			dialogFormVisible:false,
			treeshow:false,
			combinationForm:{
				defaultProps: {
				          children: 'children',
				          label: 'label'
				},
				
			},
			data: [{
			          label: '一级 1',
			          children: [{
			            label: '二级 1-1',
			            children: [{
			              label: '三级 1-1-1'
			            }]
			          }]
			        }, {
			          label: '一级 2',
			          children: [{
			            label: '二级 2-1',
			            children: [{
			              label: '三级 2-1-1'
			            }]
			          }, {
			            label: '二级 2-2',
			            children: [{
			              label: '三级 2-2-1'
			            }]
			          }]
			        }, {
			          label: '一级 3',
			          children: [{
			            label: '二级 3-1',
			            children: [{
			              label: '三级 3-1-1'
			            }]
			          }, {
			            label: '二级 3-2',
			            children: [{
			              label: '三级 3-2-1'
			            }]
			          }]
			        }],
			defaultProps: {
			          children: 'children',
			          label: 'label'
			        },
			queryForm:{
                username: "",
                sex: "",
                positionid: "",
                address: "",
				isactive:"是",
				phone:"",
				deptid:0,
				type:"",
				pageNo:1, // 当前页码
				pagesize:100 ,// 每页记录数
			},
			addDeptForm:{
				username:"",
				region:"",
				type:""
				},
			pagetotal:0,
			userRules, // 数据验证规则
            userForm: {
                id: null,
                username: "",
                sex: "",
                birthday: "",
                address: "",
                phone: "",
				dept_id:"",
				position:"",
				dept:"",
				ismanager:"",
				isleader:"",
				leaderid:"",
                password: "",
                repassword: "",
				isactive:"",
				employdate:"",
				leavedate:"",
				satus:"",
				workstatus:"",
				workplace:"",
				idcards:[], //证件照
				// 用户拥有的应用
				defaultapps:[],
				desktopapps:[]
            },
			// 所有部门
			depts:[],
			// 所有用户
			users:[],
			//职位
			positions:[],
			// 所有应用列表
			defaultapps:[],
			desktopapps:[],
			multipleSelection:[],
			pagedata:[],  // 当前页结果集
			loaded:false,
			dialogImageUrl:"",
			imgDialogVisible:false,
			queryFormVisible :false,
			addDeptFormVisible:false,
			tempfilelist:[]
        }
    },
	methods: {
		// 显示侧边栏
		showLeftBar() {
			if (this.leftbar_show) {
				this.leftbar_show = false
			} else {
				this.leftbar_show = true
			}
		},
		handleNodeClick(data) {
			this.queryForm.deptid = data.id;
			this.queryForm.type = data.type;
			this.queryForm.pageNo = 1;
			this.query();
		},
		createTempfilelist(filelist) {
			this.tempfilelist = []
			for (let s of filelist) {
				if (typeof(s.response) != "undefined") {
					this.tempfilelist.push({
						name: s.response.data.name,
						url: s.response.data.url+ "/" + localStorage.getItem('TOKEN')
					});
				} else {
					this.tempfilelist.push({
						name: s.name,
						url: s.url
					});
				}
			}
		},
		addTokenTo(res) {
			// 身份证照片URL后加TOKEN
			for (let j in res.data.idcards) {
				res.data.idcards[j].url = res.data.idcards[j].url + "/" + localStorage.getItem('TOKEN')
			}
		},
		handleRemove(file, filelist) {
			this.createTempfilelist(filelist);
		},
		handlePictureCardPreview(file) {
			this.dialogImageUrl = file.url;
			this.imgDialogVisible = true;
		},
        handleAvatarSuccess(res, file, filelist) {
			this.createTempfilelist(filelist);
        },
        beforeAvatarUpload(file) {
            const isJPG = ["image/jpeg","image/jpg","image/png"].indexOf(file.type) > -1;
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('图片只能是png,jpeg,jpg格式!');
                return false;
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
                return false;
            }
            return true;
        },
		// 表格多选
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},
		// 确认
		async cofirm(){
		    console.log(this.userForm);
            this.$refs.userForm.validate(async valid => {
                if (valid){
					// 显示加载框
					const loading = this.$loading(LOAD_STYLE);
					try {
						// 特殊处理上传证件文件列表
						this.userForm.idcards = []
						for (let i in this.tempfilelist) {
							// 去除TOKEN
							index = this.tempfilelist[i].url.lastIndexOf('/');
							this.tempfilelist[i].url = this.tempfilelist[i].url.substring(0,index)
						}
						this.userForm.idcards = this.tempfilelist;

						if (this.action=="add") {
						    console.log(this.userForm);
							let res = await axios.put('api/user/add', this.userForm);
							if (res.code === 200) {
								this.addTokenTo(res);
								this.pagedata = res.data;
								this.pagetotal = res.total;
								this.dialogFormVisible = false
								//初始组织结构
								this.getCombination()

							}else {
								this.$message.error(res.message);
							}
						} else{

							let res = await axios.put('api/user/update', this.userForm);
							if (res.code === 200) {
								this.addTokenTo(res);
								this.pagedata.splice(this.index,1,res.data);
								this.dialogFormVisible = false
								//初始组织结构
								this.getCombination()

							}else {
								this.$message.error(res.message);
							}
						}
						// 取得所有主管
						this.getAllLeader()

					}catch (e) {
						this.$message.error('请求出错！', e.message);
					}
					// 关闭加载框
					loading.close();
                }
            })
		},
		// 取得所有应用列表
		async getAllapp() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/allapp');
				if (res.code === 200) {
					this.defaultapps = deepCopy(res.data.defaultapps);
					this.desktopapps = deepCopy(res.data.desktopapps);
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();
		},
		// 取得组织结构
		async getCombination() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			this.treeshow = false;
			try {
				let res = await axios.get('api/detp/combination');
				if (res.code === 200) {
					this.combinationForm.data = deepCopy(res.data);
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('组织结构请求出错！', e.message);
			}

			this.treeshow = true;


			// 关闭加载框
			loading.close();
		},
		// 取得所有部门列表
		async getAllDept() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/alldept');
				if (res.code === 200) {
					this.depts = res.data;
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();
		},
		// 取得所有职位列表
		async getAllPosition() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/allposition');
				if (res.code === 200) {
					this.positions = res.data;
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			// 关闭加载框
			loading.close();
		},
		// 取得所有主管
		async getAllLeader() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/leader/all');
				if (res.code === 200) {
					this.users = res.data;
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();
		},

		start(){
			this.queryForm.pageNo = 1
			this.query()
		},
		//add dept
		async adddeptuser(){
			this.$refs.addDeptForm.validate(async valid => {
			    if (valid){
			console.log(this.addDeptForm)
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.post('api/user/addDeptGroup', this.addDeptForm);
				if (res.code === 200) {
					this.addDeptFormVisible =false
					this.$message.success(res.message);
					//初始组织结构
					//this.getCombination()
					//初始化部门列表
					this.getAllDept();
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();
			}
			})
			},
		// 查询
		async query() {
		    console.log(this.positionid);
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.post('api/user/query', this.queryForm);
				if (res.code === 200) {
					// 身份证照片URL后加TOKEN
					for (let i in res.data) {
						for (let j in res.data[i].idcards) {
							res.data[i].idcards[j].url = res.data[i].idcards[j].url + "/" + localStorage.getItem('TOKEN')
						}
					}

					this.pagedata = res.data;
					this.pagetotal = res.total;
					this.$message.success(res.message);
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();
		},
		toolAction(acName) {
			if (acName == "添加") {
				this.add()
			} else if (acName == "过滤条件") {
				this.queryFormVisible=true;
			} else if (acName == "删除") {
				this.delete()
			}
		},
		actionQuery() {
			this.query();
			this.queryFormVisible=false;
		},
		// async delete() {
		// 	try {
		// 		ids =[]
		// 		for (let user of this.multipleSelection) {
		// 			ids.push(user.id)
		// 		}
		// 		if (ids.length > 0) {
		// 			this.$confirm('此操作将永久删除选定的用户, 是否继续?', '提示', {
		// 			                confirmButtonText: '确定',
		// 			                cancelButtonText: '取消',
		// 			                type: 'warning'
		// 			            }).then(async () => {
		// 							let res = await axios.put('api/user/delete', ids);
		// 							if (res.code === 200) {
		// 								for (var i = this.tableData.length-1;i>=0;i--) {
		// 									if (ids.includes(this.tableData[i].id)) {
		// 										this.tableData.splice(i,1);
		// 									}
		// 								}
		// 								this.pageNo = 1
		// 								this.loadPageData();
		// 								this.dialogFormVisible = false
		// 							}else {
		// 								this.$message.error(res.message);
		// 							}
		// 			            }).catch((e) => {
		// 			                if (e.message) this.Msg('error', e.message);
		// 			            });
		// 		} else {
		// 			this.$message.error('请先选择要删除的数据行！');
		// 		}
		// 	}catch (e) {
		// 		this.$message.error('请求出错！', e.message);
		// 	}
		// },
		selectionChange(selection){
			this.selection = selection
		},
		adddeptgroup(){
			if (this.queryForm.deptid == 0) {
						this.$message({
							type: 'info',
							message: '请选择部门或分组节点。'
						});
						return
			}
			this.addDeptFormVisible= true;

			this.addDeptForm= {
			    region:"",
			    deptname: "",
				type:""
			}
			this.addDeptForm.region =this.queryForm.deptid
		},
		//
		removedeptgroup() {
			if (this.depts.length > 0) {
				if (true) {
					this.$confirm('确定要将数据删除吗?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(async () => {
						this.removedept()
					}).catch((e) => {
						this.$message({
							type: 'info',
							message: '已取消删除'
						});
					});
				} else {

				}
			} else {
				this.$message.error('请选择数据行！');
			}
		},
		async removedept(){

			if(this.pagetotal==0){
				try {
					let res = await axios.post('api/user/removedept', this.queryForm);
					if (res.code === 200) {
						//this.getCombination()
						//初始化部门列表
						this.getAllDept();

						this.$message.success(res.message);
					}else {
						this.$message.error(res.message);
					}
				}catch (e) {
					this.$message.error('请求出错！', e.message);
				}
			}else{
				this.$message.error("该部门下有人，不能删除！");
				return false;
			}
		},
		add() {
			this.action="add";
			this.dialogFormVisible = true;
            this.userForm= {
                id: null,
                username: "",
                sex: "",
                birthday: "",
                address: "",
                phone: "",
                password: "",
                repassword: "",
				dept_id:"",
				position:"",
				dept:"",
				isleader:"否",
				isactive:"是",
				idcards:[],
				employdate:"",
				leavedate:"",
				status:"在职",
				workstatus:"试用期",
				workplace:"在家",
				// 用户拥有的应用
				defaultapps:[],
				desktopapps:[]
            }
			this.tempfilelist = [];
		},
		// 编辑
		edit(index, row) {
			this.action="edit"
			this.index = index;
			this.dialogFormVisible = true;
			this.userForm = deepCopy(row)
		},
		// 设定表格当前页
		handleCurrentPageChange (selectedPageNo) {
		  this.queryForm.pageNo = selectedPageNo
		  // 加载数据页
		  this.query()
		},
	},
	async mounted() {
		console.log(this.queryForm);
		// 自动调整表格高度
		window.onresize = () => {
		  return (() => {
			this.tableHeight = window.innerHeight - 180
		  })()
		}
		//初始化应用列表
		this.getAllapp();
		//初始化部门列表
		this.getAllDept();
		//初始化职位列表
		this.getAllPosition();
		//初始组织结构
		this.getCombination()
		// 取得所有主管
		this.getAllLeader()
		// 初始化用户列表
		this.query();

	}

});	